import React, { useState, useRef } from "react";
import {
  TextField,
  IconButton,
  Box,
  Chip,
  Stack,
  Typography,
} from "@mui/material";
import { Send, AttachFile, Close } from "@mui/icons-material";

interface FileData {
  name: string;
  size: number;
  type: string;
  file: File;
}

interface MessageInputProps {
  onSend: (message: string, files: FileData[]) => void;
}

const MessageInput: React.FC<MessageInputProps> = ({ onSend }) => {
  const [message, setMessage] = useState("");
  const [files, setFiles] = useState<FileData[]>([]);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleMessageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setMessage(e.target.value);
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const newFiles = Array.from(e.target.files).map((file) => ({
        name: file.name,
        size: file.size,
        type: file.type,
        file,
      }));
      setFiles((prev) => [...prev, ...newFiles]);
    }
  };

  const handleRemoveFile = (index: number) => {
    setFiles((prev) => prev.filter((_, i) => i !== index));
  };

  const handleSend = () => {
    if (message.trim() || files.length > 0) {
      onSend(message, files);
      setMessage("");
      setFiles([]);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  return (
    <Box sx={{ position: "relative" }}>
      <TextField
        fullWidth
        multiline
        maxRows={4}
        value={message}
        onChange={handleMessageChange}
        onKeyPress={handleKeyPress}
        placeholder="メッセージを入力する"
        InputProps={{
          startAdornment:
            files.length > 0 ? (
              <Stack
                direction="row"
                spacing={1}
                sx={{
                  flexWrap: "wrap",
                  gap: 1,
                  mb: 1,
                  width: "100%",
                }}
              >
                {files.map((file, index) => (
                  <Chip
                    key={index}
                    label={`${file.name} (${Math.round(file.size / 1024)} KB)`}
                    onDelete={() => handleRemoveFile(index)}
                    deleteIcon={<Close />}
                    variant="outlined"
                    size="small"
                  />
                ))}
              </Stack>
            ) : undefined,
          sx: {
            alignItems: "flex-start",
            ...(files.length > 0 && {
              pt: 4,
              "& textarea": {
                mt: files.length > 0 ? 0 : undefined,
              },
            }),
          },
          endAdornment: (
            <>
              <IconButton
                onClick={() => fileInputRef.current?.click()}
                edge="end"
                sx={{ alignSelf: "flex-end" }}
              >
                <AttachFile />
              </IconButton>
              <input
                type="file"
                ref={fileInputRef}
                onChange={handleFileChange}
                style={{ display: "none" }}
                multiple
              />
              <IconButton
                onClick={handleSend}
                disabled={!message.trim() && files.length === 0}
                edge="end"
                color="primary"
                sx={{ alignSelf: "flex-end" }}
              >
                <Send />
              </IconButton>
            </>
          ),
        }}
      />
    </Box>
  );
};

export default MessageInput;
